<?php
namespace EShop;

use Cache\Redis as Cache;
use JonnyW\PhantomJs\Client;
use JonnyW\PhantomJs\DependencyInjection\ServiceContainer;

class AutoTester
{
    protected $uid;
    protected $platform;
    protected $sequence;
    const TASK_CACHE_KEY = 'EShop:task_cache_key';
    public function __construct($uid, $platform)
    {

    }

    public function run(array $data)
    {

    }

    public function requester()
    {
        if($renew || !($data = Cache::get($key))){
            $url = $this->home_url;

            $phantomjs_bin = ROOT_PATH.'bin'.DIRECTORY_SEPARATOR.'phantomjs.exe';

            $proc_dir = ROOT_PATH.'phantomjs'.DIRECTORY_SEPARATOR.'php_phantomjs';

            $serviceContainer = ServiceContainer::getInstance();

            $procedureLoader = $serviceContainer->get('procedure_loader_factory')->createProcedureLoader($proc_dir);

            $client = Client::getInstance();

            $client->getEngine()->setPath($phantomjs_bin);

            $client->setProcedure('jd_login');

            $client->getProcedureLoader()->addLoader($procedureLoader);

            $request  = $client->getMessageFactory()->createRequest($url, 'GET');

            $request->setHeaders($this->getHeaders());

            $response = $client->getMessageFactory()->createResponse();

            if($data = $client->send($request, $response)->content){
                Cache::set($key, serialize($data), $this->cache_ttl);
            }
        }
    }

    public function buildRequestData($data = '', $cookie = '')
    {

        $http_headers = [
            'cookie' => $cookie,
        ];

        $params = [
            'data' => $data,
            'user_id' => $this->uid,
            'channel' => $this->platform,
            'http_headers' => json_encode($http_headers, JSON_UNESCAPED_UNICODE),
        ];

        $params = array_filter($params);

        $this->sequence and $params['sequence'] = $this->sequence;

        $params_str = 'app_id=10001&ts=1476435524415&sign=63187d6a0515fe37a65f2fe6b5f19b80&data=';


        echo $params_str.urlencode(json_encode($params, JSON_UNESCAPED_UNICODE));


    }

    protected function getLastTask()
    {
        if($data = Cache::get(static::TASK_CACHE_KEY)){
            return is_array($data) ? $data : unserialize($data);
        }
    }

    protected function saveTask(array $task)
    {
        return $task ? Cache::set(static::TASK_CACHE_KEY, serialize($task)) : 0;
    }
}
